<template>
  <div class="box">
    <div
      v-for="(item, index) in list"
      class="item"
      :class="{ selected: select == index }"
      @click="select = index"
    >
      <span class="name">
        {{ item.templateName }}
      </span>
      <span class="btn">
        <el-button type="warning" link @click="PreviewRow(item)">
          预览
        </el-button>
        <el-button type="danger" link @click="DeleteRow(item)">删除</el-button>
      </span>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from "vue";
import { useRouter } from "vue-router";
import request from "@/libs/request";
import * as Table from "@/libs/table";

const router = useRouter();
const list = ref([]);
const select = ref(-1);
let loading = null;

const GetList = () => {
  request({
    url: import.meta.env.VITE_APP_ENV + "/template/list",
    method: "get",
  })
    .then((res) => {
      list.value = res.rows;
      loading?.close();
      loading = null;
    })
    .catch(() => {
      loading?.close();
      loading = null;
    });
};

const PreviewRow = (data) => {
  window.open(
    router.resolve({ path: "/report", query: { templateId: data.templateId } })
      .href
  );
};

const DeleteRow = (data) => {
  ElMessageBox.confirm(`是否确定删除【${data.templateName}】表格？`, "删除", {
    distinguishCancelAndClose: true,
    confirmButtonText: "确定",
    cancelButtonText: "取消",
  }).then(() => {
    loading = ElLoading.service({
      lock: true,
      text: "Getting...",
      background: "rgba(0, 0, 0, 0.7)",
    });
    request({
      url: import.meta.env.VITE_APP_ENV + "/template/" + data.templateId,
      method: "delete",
    })
      .then(() => {
        ElMessage({
          type: "success",
          message: "删除成功！",
        });
        GetList();
      })
      .catch(() => {
        loading?.close();
        loading = null;
      });
  });
};

const Ready = (callback) => {
  if (select.value < 0) {
    ElMessage({
      message: "请选择一个表格！",
      type: "warning",
    });
    return;
  }
  Table.LoadTable(list.value[select.value]);
  callback(true);
};

defineExpose({
  Ready,
});

onMounted(() => {
  loading = ElLoading.service({
    lock: true,
    text: "Getting...",
    background: "rgba(0, 0, 0, 0.7)",
  });
  GetList();
});
</script>

<style lang="scss" scoped>
.box {
  width: 800px;
  height: 500px;
  overflow: auto;

  .item {
    line-height: 36px;
    padding: 0 8px;

    &:hover {
      background: #eee;
    }

    &:active {
      background: #ccc;
    }

    .btn {
      float: right;
    }
  }

  .selected {
    background: #eee;
  }
}
</style>
